package com.roy.sms.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.springframework.stereotype.Service;

import com.roy.sms.dao.RoleDao;
import com.roy.sms.dao.UserDao;
import com.roy.sms.model.Column;
import com.roy.sms.model.User;
import com.roy.sms.util.Pager;
import com.roy.sms.util.StringUtil;
import com.roy.sms.vo.UserVO;

@Service
public class UserService {

	@Resource
	private UserDao userDao;
	
	@Resource
	private RoleDao roleDao;
	
	@Transactional
	public void add(UserVO userVO){
		userDao.add(userVO.getUser());
	}
	
	@Transactional
	public void update(UserVO userVO){
		User user = userVO.getUser();
		userDao.update(user);
	}
	
	@Transactional
	public Pager<UserVO> findPage(int rowBeginIndex, int rowCount){
		Pager<UserVO> pager = new Pager<UserVO>();
		pager.setTotal(userDao.findCount());
		List<User> users = userDao.findPage(rowBeginIndex, rowCount);
		List<UserVO> userVOS = new ArrayList<UserVO>();
		for(User user: users){
			userVOS.add(new UserVO(user));
		}
		pager.setRows(userVOS);
		return pager;
	}
	
	@Transactional
	public void deleteUsers(String ids){
		if(!StringUtil.isEmpty(ids)){
			String[] sid = ids.split(",");
			for(String id : sid){
				userDao.delete(Integer.valueOf(id));
			}
		}
	}
	
	@Transactional
	public UserVO loadUser(int id){
		User user = userDao.load(id);
		return new UserVO(user);
	}
	
	@Transactional
	public User login(String username,String password){
		return userDao.login(username, password);
	}
	
	@Transactional
	public List<Column> getUserColumns(User u){
		return roleDao.queryUserColumn(u);
	}
	
}
